<template>
  <div class="coor-postil">
    <el-form
      ref="postilForm"
      :model="postilForm"
      :rules="rules"
    >
      <el-form-item
        class="toggle-btn"
        style="text-align: right;margin-bottom: 0"
      >
        <el-button
          @click="toggleInput"
          type="text"
          size="small"
        >
          {{ showUEditor ? '切换纯文本' : '切换富文本' }}
          <i class="jeicon jeicon-mobile-o" />
        </el-button>
      </el-form-item>
      <el-form-item
        class="postil-editor"
        prop="content"
      >
        <div
          id="postil-uEditor"
          v-show="showUEditor"
          style="height: 260px"
        />
        <el-input
          ref="postilTextarea"
          v-show="!showUEditor"
          :autosize="{ minRows: 6, maxRows: 6}"
          v-model="postilForm.content"
          resize="none"
          type="textarea"
        />
      </el-form-item>
      <el-form-item>
        <el-dropdown
          @command="handleCommand"
          :placement="'top'"
          :show-timeout="100"
          :hide-timeout="100"
          :size="'medium'"
        >
          <i class="fa fa-at" />
          <el-dropdown-menu
            slot="dropdown"
            class="je-postil-downmenu"
          >
            <el-dropdown-item
              command="choose"
              icon="fe icon-menu-1"
            >
              选择
            </el-dropdown-item>
            <el-dropdown-item
              command="curuser"
              icon="jeicon jeicon-me2-on"
            >
              登记人
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span class="at">
          {{ names.join(',') }}
        </span>
        <el-button
          @click="onPublish"
          size="mini"
          class="darkBtn issueBtn"
        >
          {{ langLocal.publishButton }}
        </el-button>
        <el-button
          @click="onCancel"
          size="mini"
          class="darkBtn"
        >
          {{ langLocal.cancelButton }}
        </el-button>

        <el-button
          v-if="params.showOtherBtn"
          @click="openDetails"
          type="primary"
          size="mini"
        >
          {{ langLocal.viewDetails }}
        </el-button>
      </el-form-item>
    </el-form>

    <div class="postilList">
      <div
        v-for="(item, index) in postilObj.rows"
        :key="index"
        class="postilItem"
      >
        <div class="title">
          <span class="left">
            <i class="fa fa-commenting" />
            <span>{{ item.SY_CREATEUSERNAME }}</span> {{ langLocal.atText }}
            <span style="color: blue">{{ item.SY_CREATETIME.substring(0,16) }}</span>
            <span v-if="!item.POSTIL_HFRID">批注</span>
            <span v-if="item.POSTIL_HFRID">{{ langLocal.replyText }}</span>
            <span v-if="item.POSTIL_HFRID">{{ item.POSTIL_HFR }}</span> :
          </span>
          <span class="right">
            <el-button
              @click="postilReply(item)"
              size="mini"
              type="primary"
            >{{ langLocal.replyText }}</el-button>
            <el-button
              v-if="getUserId == item.SY_CREATEUSERID"
              @click="postilDelete(item,index)"
              size="mini"
              type="danger"
              class="delBtn"
            >{{ langLocal.deleteText }}</el-button>
          </span>
        </div>
        <div
          v-html="item.POSTIL_PZ"
          class="postil-content"
        />
      </div>
    </div>
  </div>
</template>
<script>
import getMaxZindex from '../../../../modules/microMail/util/getZindex';

export default {
  name: 'JeVuePostil',
  components: {},
  props: {
    params: {
      type: Object,
      default: () => { },
    },
  },
  data() {
    return {
      showUEditor: false,
      UEditor: null,
      postilForm: {
        content: '',
      },
      rules: {
        content: [
          { required: true, message: ' ', trigger: 'blur' },
        ],
      },
      langLocal: '', // 本地语言
      ids: [],
      names: [],
      toId: '', // 回复对象的ID
      postilObj: {},
      funcData: JE.getFuncData(this.params.funcCode),
    };
  },
  computed: {
    getUserId() {
      return JE.currentUser.userId;
    },
  },
  mounted() {
    this.langLocal = JE.getLocalLang('sys.cooperation');
    this.initPostil(this.params);
    this.$nextTick(() => {
      $('.postilList').css({ height: `${$('.je-drawer').height() - 310}px` });
      this.initEditor();
    });
    console.log(this.params);
  },
  methods: {
    // 切换文本框
    toggleInput() {
      this.showUEditor = !this.showUEditor;
      if (this.showUEditor) {
        this.$nextTick(() => {
          $('.postilList').css({ height: `${$('.je-drawer').height() - 465}px` });
          // 桌面端图片链接处理
          this.postilForm.content = JE.buildUeditorImgUrl(this.postilForm.content);
          this.UEditor && this.UEditor.setContent(`<p>${this.postilForm.content}</p>`);
        });
      } else {
        $('.postilList').css({ height: `${$('.je-drawer').height() - 310}px` });
        this.postilForm.content = '';
      }
    },
    initEditor() {
      // 富文本编辑器
      const editorCfg = {
        autoHeightEnabled: false,
        enableAutoSave: false,
        allowDivTransToP: false, // 阻止div标签自动转换为p标签
        toolbars: [[
          'undo', 'redo', '|',
          'bold', 'italic', 'underline', 'forecolor', 'backcolor', 'fontfamily', 'fontsize', '|',
          'insertorderedlist', 'insertunorderedlist', '|',
          'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',
        ]],
        // 关闭字数统计
        wordCount: false,
        maximumWords: 100000000000000,
        // 关闭elementPath
        elementPathEnabled: false,
      };
      this.UEditor = UE.getEditor('postil-uEditor', editorCfg);

      this.UEditor.ready(() => {
        // 处理编辑器toolbar下拉选择  被遮挡的问题
        $('#postil-uEditor .edui-editor').css({ 'z-index': getMaxZindex() + 1 });
      });
    },
    // 回复
    postilReply(em) {
      this.$refs.postilTextarea.focus();
      this.toId = em.JE_CORE_POSTIL_ID;
      this.names = [];
      this.ids = [];
      this.names.push(em.SY_CREATEUSERNAME);
      this.ids.push(em.SY_CREATEUSERID);
      this.postilForm.content = '';
    },
    // 删除
    postilDelete(em, index) {
      const that = this;
      JE.confirm(this.langLocal.messagesOne, (btn) => {
        if (btn == 'ok') {
          JE.ajax({
            url: JE.getUrlMaps('je.core.remove'),
            params: {
              tableCode: 'JE_CORE_POSTIL',
              ids: em.JE_CORE_POSTIL_ID,
            },
          });
          that.postilObj.rows.splice(index, 1);
          that.$emit('getPostilNum', that.postilObj.rows.length); // 刷新角标
        }
      });
    },
    // 首页点击查看详情跳转功能弹窗
    openDetails() {
      // 获得数据
      const that = this;
      const obj = JE.ajax({
        url: JE.getUrlMaps('je.core.getInfoById'), // 获得数据的地址
        params: {
          // 视图功能应该取的是视图的数据，否则会导致数据不完整
          tableCode: Ext.value(that.funcData.info.viewTableName, that.funcData.info.tableName),
          pkValue: that.params.pkValue,
        },
      });
      JE.showFunc(that.params.funcCode, {
        type: 'form',
        values: obj,
      });
      this.$emit('lookdetail');
    },
    // 发布
    onPublish() {
      if (!this.postilForm.content.trim() && !this.UEditor.getContent().trim()) {
        return JE.msg('批注内容不能为空，请输入!');
      }
      const that = this;
      // 批注数据
      const titleConfig = JE.getObjAttr(this.funcData.info.otherConfig, 'titleConfig');
      const postilDatas = JE.ajax({
        // url:JE.getUrlMaps("je.core.savePostil"),
        url: '/je/postil/postil/savePostil',
        params: {
          POSTIL_HFRID: that.ids.join(','),
          POSTIL_HFR: that.names.join(','),
          POSTIL_PZ: that.showUEditor ? that.UEditor.getContent() : that.postilForm.content,
          POSTIL_FUNCID: that.funcData.info.funcId,
          POSTIL_FUNCCODE: that.funcData.info.funcCode,
          POSTIL_FUNCNAME: that.funcData.info.funcName,
          SY_PARENT: that.toId,
          POSTIL_FUNCNR: JE.toXT(titleConfig, { bean: this.params.bean }),
          POSTIL_FUNCCLS: that.funcData.info.funcIconCls,
          POSTIL_TABLECODE: that.funcData.info.tableName,
          POSTIL_MODELID: that.params.pkValue,
          tableCode: 'JE_CORE_POSTIL',
        },
      });
      if (postilDatas.length > 0) {
        this.postilForm.content = '';
        this.UEditor && this.UEditor.setContent('');
        this.names = [];
        this.ids = [];
        postilDatas.forEach((item) => {
          this.postilObj.rows.unshift(item);
        });
        this.$emit('getPostilNum', this.postilObj.rows.length); // 刷新角标
      }
    },
    // 取消
    onCancel() {
      this.postilForm.content = '';
      this.UEditor && this.UEditor.setContent('');
      this.names = [];
      this.ids = [];
    },
    // 初始化加载列表
    initPostil(cfg) {
      const { pkValue } = cfg;
      const { info } = this.funcData;

      const whereSql = ` AND POSTIL_FUNCID='${info.funcId}' AND POSTIL_MODELID='${pkValue}'`;
      const that = this;
      JE.ajax({
        url: JE.getUrlMaps('je.core.load'),
        async: true,
        params: {
          whereSql,
          orderSql: 'ORDER BY SY_CREATETIME DESC',
          j_query: Ext.encode({
            custom: [
              { type: '=', code: 'POSTIL_FUNCID', value: info.funcId },
              { type: '=', code: 'POSTIL_MODELID', value: pkValue },
            ],
            order: [{ code: 'SY_CREATETIME', type: 'desc' }],
          }),
          limit: -1,
          tableCode: 'JE_CORE_POSTIL',
        },
        success(res) {
          that.postilObj = JE.getAjaxData(res);
          that.$emit('getPostilNum', that.postilObj.rows.length); // 刷新角标
        },
        failure(response) {
          JE.error(response.responseText, '', JE.format(JE.local.lang.core.util.Util.ajaxError), {});
        },
      });
    },
    handleCommand(command) {
      if (command == 'choose') {
        this.selectUser();
      } else if (this.ids.indexOf(this.params.bean.SY_CREATEUSERID) == -1) {
        this.ids.push(this.params.bean.SY_CREATEUSERID);
        this.names.push(this.params.bean.SY_CREATEUSERNAME);
      }
    },
    // 选择人
    selectUser() {
      const that = this;
      JE.vue.selectUser({
        title: that.langLocal.win.popleText,
        height: JE.getBodyHeight() > 650 ? 650 : JE.getBodyHeight() - 150,
        configInfo: 'JE_CORE_DEPTUSER_NODISABLE,,,M',
        type: 'tree',
        value: that.ids.join(','),
        valueType: 'id',
        callback(recs) {
          that.names = [];
          that.ids = [];
          Ext.each(recs, (rec) => {
            that.names.push(rec.text);
            that.ids.push(rec.id);
          });
        },
      });
    },
  },
};
</script>
<style lang="scss">
.coor-postil {
  .el-form-item__content {
    padding: 0 30px;
    display: flex;
    line-height: normal;
    align-items: center;
    .darkBtn {
      background-color: #ddd;
      color: #606266;
      border-color: #ddd;
    }
    .issueBtn{
      background-color: #F56C6C;
      border-color: #F56C6C;
      color: #fff;
    }
    .fa-at {
      color: rgb(64, 142, 186);
      cursor: pointer;
      margin-right: 10px;
    }
    .at {
      margin-right: 10px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 590px;
    }
  }
  .toggle-btn {
    .el-form-item__content {
      justify-content: flex-end;
      margin-bottom: 0;
    }
  }
  .postilList {
    padding: 0 43px;
    overflow-y: auto;
    .postilItem {
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 10px;
      .title {
        display: flex;
        align-items: center;
        .left {
          flex: 1;
          color: #50697e;
        }
      }
      .postil-content {
        color: #808080;
        padding: 16px;
        white-space: pre-line;
        word-break: break-word;
        padding-top: 10px;
        font-size: 14px;
        img {
          max-width: 100%;
        }
      }
    }
    .postilItem:last-child {
      border-bottom: 0;
    }
  }
  .el-button--primary {
    background-color: #386ad0;
    border-color: #386ad0;
  }
  .el-button--primary:hover {
    background-color: #409eff;
    border-color: #409eff;
  }
  .delBtn{
    background-color: #ddd !important;
    border-color:#ddd !important;
    color:#606266 !important ;
  }
  .delBtn:hover{
    background-color: #F5F5F5 !important;
    border-color: #F5F5F5 !important;
  }
}
.je-postil-downmenu {
  z-index: 9999999 !important;
  padding: 0;
  .el-dropdown-menu__item {
    line-height: 45px;
    &:first-child {
      border-bottom: 1px solid #ddd;
    }
  }
}
</style>
